#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC3010
#
# Pico UPS Daemon starting and stopping
#

DAEMON="picod"
PIDFILE="/var/run/${DAEMON}.pid"

PATH=/sbin:/bin:/usr/sbin:/usr/bin

test -x "/opt/picod/${DAEMON}" || exit 0

case $1 in
	start)
		echo -n "Starting PIco UPS daemon: "

		# find out if a PIco UPS unit is installed at all
		if i2cget -y 1 0x69 0x26 2>/dev/null >/dev/null; then

			# lets set the battery runtime to 0xff (until 3.5v)
			i2cget -y 1 0x6b 0x09 0xff 2>/dev/null >/dev/null

			# now start the daemon
			if start-stop-daemon --start --background --pidfile "${PIDFILE}" --make-pidfile --quiet --exec "/opt/picod/${DAEMON}.sh"; then
				echo "OK"
			else
				echo "FAIL"
			fi
		else
			echo "no hardware found"
		fi
	;;

	stop)
		echo -n "Stopping PIco UPS daemon: "
		if [[ -f ${PIDFILE} ]]; then
			if start-stop-daemon --stop --quiet --pidfile "${PIDFILE}"; then
				echo "OK"
			else
				echo "FAIL"
			fi
			rm -f "${PIDFILE}"
		else
			echo "OK"
		fi
	;;

	restart|force-reload)
		$0 stop
		sleep 1
		$0 start
	;;

	*)
		echo "Usage: $0 {start|stop|restart|force-reload}" >&2
		exit 1
	;;
esac

exit 0
